
const {ccclass, property} = cc._decorator;

@ccclass
export default class SpriteSplit extends cc.Component {
    @property(cc.SpriteFrame)
    private sprite:cc.SpriteFrame = null
    // LIFE-CYCLE CALLBACKS:
    private spriteframes:cc.SpriteFrame[] = [];

    @property(cc.Integer)
    x:number = 0;
    @property(cc.Integer)
    y:number = 0;

    @property(cc.Boolean)
    isRun: boolean = false;

    private curSpFrameIndex:number = 0;


    onLoad () {
        // 背景图片对象
        // console.log(this.getComponent(cc.Sprite));
        
        this.getSplit(this.x, this.y);

        // this.curSpFrame = this.getComponent(cc.Sprite).spriteFrame;
        
        this.getComponent(cc.Sprite).spriteFrame = this.getSprite(this.curSpFrameIndex);
        if (this.isRun) {
            // 设置定时器 cc.macro.REPEAT_FOREVER默认无限循环
            this.schedule(()=>{
                this.spriteRun();
            }, 0.1, cc.macro.REPEAT_FOREVER);
        }
    }

    // 获取贴图
    getSprite(i):cc.SpriteFrame {
        return this.spriteframes[i];
    }
    // 拆分贴图
    getSplit(x:number, y:number) {
        // getOriginalSize获取图片原始大小
        let width = this.sprite.getOriginalSize().width / x;
        let height = this.sprite.getOriginalSize().height / y;
        
        for(let i = 0; i < x*y; i++) {
            let curX = width * i % (this.sprite.getOriginalSize().width);
            let curY = height * Math.floor(i / x);
            let tmpRect = new cc.Rect(curX, curY, width, height);
            let spriteClone:cc.SpriteFrame = this.sprite.clone(); //克隆
            spriteClone.setRect(tmpRect);
            
            this.spriteframes[i] = spriteClone;
        }
        // console.log(this.spriteframes);
    }
    // 精灵动画运行
    spriteRun() {
        if (this.curSpFrameIndex <= (this.x*this.y - 2) ) {
            this.curSpFrameIndex ++;
        } else {
            this.curSpFrameIndex = 0;
        }
        this.getComponent(cc.Sprite).spriteFrame = this.getSprite(this.curSpFrameIndex);
    }

    start () {

    }

    update (dt) {
    }
}
